package cn.zhz.privacy.handler;

import cn.zhz.privacy.annotation.FieldDesensitize;
import cn.zhz.privacy.enums.SerializeType;
import cn.zhz.privacy.sensitive.SensitiveType;
import cn.zhz.privacy.sensitive.SensitiveTypeRegisty;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 脱敏
 * @author ZHZ
 * @since 2023-03-07
 */
public class DesensitizeHandler extends AbstractHandler<FieldDesensitize> implements ApplicationContextAware {
    private ApplicationContext applicationContext;
    private static final Map<Class<?>, List<Field>> FIELD_CACHE = new ConcurrentHashMap<>();

    public DesensitizeHandler() {
        super(FieldDesensitize.class);
    }

    protected Map<Class<?>, List<Field>> getFieldCache() {
        return FIELD_CACHE;
    }

    @Override
    public boolean canHandleParameter(Class<?> clazz) {
        return false;
    }

    @Override
    String getAfterValue(FieldDesensitize annotation, String originalValue, SerializeType serializeType) {
        SensitiveType sensitiveType = annotation.value();
        return SensitiveTypeRegisty.get(sensitiveType).handle(String.valueOf(originalValue));
    }

    @Override
    public void handleParam(Object parameter) {
    }

    /**
     * 处理结果集
     *
     * @param resultList
     */
    @Override
    public void handleResultList(List<Object> resultList) {
        resultList.forEach(object -> {
            if (object != null) {
                handleObject(object, object.getClass(), SerializeType.ENCRYPT);
            }
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
